// 获取用户信息
$.ajax({
    type: 'get',
    url: '/userInfo',
    success: function (body) {
        let userStatsDiv = document.querySelector('#user-stats');
        userStatsDiv.innerHTML = `
                    <div class="stat-item">
                        <span class="stat-label">玩家:</span>
                        <span class="stat-value">${body.username}</span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-label">分数:</span>
                        <span class="stat-value">${body.score}</span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-label">比赛场次:</span>
                        <span class="stat-value">${body.totalCount}</span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-label">获胜场数:</span>
                        <span class="stat-value">${body.winCount}</span>
                    </div>
                `;
    },
    error: function () {
        window.toast = showToast('获取用户信息失败', 'error');
    }
});

// 初始化WebSocket连接
let websocketUrl = 'ws://' + location.host + '/findMatch';
let websocket = new WebSocket(websocketUrl);

// WebSocket连接打开事件
websocket.onopen = function () {
    console.log("WebSocket连接已建立");
};

// WebSocket连接关闭事件
websocket.onclose = function () {
    console.log("WebSocket连接已关闭");
};

// WebSocket连接错误事件
websocket.onerror = function () {
    console.log("WebSocket连接出错");
};

// 页面关闭前关闭WebSocket连接
window.onbeforeunload = function () {
    websocket.close();
};

// 处理服务器返回的消息
websocket.onmessage = function (e) {
    //这个返回的响应对应"开始匹配"/"结束匹配"
    //将json转为js对象
    let resp = JSON.parse(e.data);
    let matchButton = document.querySelector('#match-button');

    if (!resp.ok) {
        console.log("游戏大厅中接收到了失败响应! " + resp.reason + resp.message);
        return;
    }

    // 开始匹配请求发送成功
    if (resp.message == 'startMatch') {
        console.log("进入匹配队列成功!");
        matchButton.textContent = '匹配中...(点击停止)';
        matchButton.classList.add('matching');
        document.body.classList.add('matching-mode');
    }
    // 结束匹配请求发送成功
    else if (resp.message == 'stopMatch') {
        console.log("离开匹配队列成功!");
        matchButton.textContent = '开始匹配';
        matchButton.classList.remove('matching');
        document.body.classList.remove('matching-mode');
    }
    // 统计在线
    else if (resp.message == 'onlineStats') {
        $('#online-count').text(resp.totalOnline);
    }
    // 匹配到对手
    else if (resp.message == 'matchSuccess') {
        console.log("匹配到对手! 进入游戏房间!");
        window.toast = showToast('匹配到对手 即将进入对战', 'success');
        // 匹配成功的动画效果
        const successAnimation = document.createElement('div');
        successAnimation.className = 'match-success-animation';
        document.body.appendChild(successAnimation);
        setTimeout(() => {
            successAnimation.remove();
            location.replace("/game_room.html");
        }, 1200);
    }
    // 检测到多开
    else if (resp.message == 'repeatConnection') {
        window.toast = showToast('当前检测到多开 请使用其他账号登录', 'error');
        setTimeout(() => {
            location.replace("/login.html");
        }, 1200);
    }
    // 其他非法响应
    else {
        console.log("收到了非法的响应! message=" + resp.message);
        window.toast = showToast('数据非法 查看控制台', 'error');
    }
};

// 匹配按钮点击事件
document.querySelector('#match-button').addEventListener('click', function () {
    //在出发websocket请求之前,先检查连接
    if (websocket.readyState === WebSocket.OPEN) {
        if (this.textContent === '开始匹配') {
            websocket.send(JSON.stringify({message: 'startMatch'}));
        } else if (this.textContent === '匹配中...(点击停止)') {
            websocket.send(JSON.stringify({message: 'stopMatch'}));
        }
    } else {
        window.toast = showToast('当前您的连接已断开 请重新登录!', 'error');
        setTimeout(() => {
            location.replace("/login.html");
        }, 1200);
    }
});


// 获取排行榜数据
function fetchLeaderboard() {
    $.ajax({
        type: 'get',
        url: '/getAllUsers',
        success: function(data) {
            renderLeaderboard(data);
        },
        error: function() {
            window.toast = showToast('获取排行榜失败', 'error');
        }
    });
}

// 渲染排行榜
function renderLeaderboard(players) {
    const leaderboardList = document.getElementById('leaderboard-list');
    leaderboardList.innerHTML = '';

    const topPlayers = players.sort((a, b) => b.score - a.score).slice(0, 10);

    topPlayers.forEach((player, index) => {
        const rankClass = index < 3 ? 'top3' : '';
        const winRate = player.totalCount > 0
            ? Math.round((player.winCount / player.totalCount) * 100)
            : 0;

        const playerElement = document.createElement('div');
        playerElement.className = 'leaderboard-item';
        playerElement.innerHTML = `
            <div class="leaderboard-rank ${rankClass}">${index + 1}</div>
            <div class="leaderboard-info">
                <div class="leaderboard-username">${player.username}</div>
                <div class="leaderboard-stats">
                    <span class="leaderboard-score">分数: ${player.score}</span>
                    <span class="leaderboard-winrate">胜率: ${winRate}%</span>
                </div>
            </div>
        `;

        leaderboardList.appendChild(playerElement);
    });
}

// 显示排行榜模态窗
function showLeaderboardModal() {
    const modal = document.getElementById('leaderboard-modal');
    modal.classList.add('active');

    // 点击关闭按钮或模态窗外部关闭模态窗
    document.querySelector('.close-modal').addEventListener('click', () => {
        modal.classList.remove('active');
    });

    modal.addEventListener('click', (e) => {
        if (e.target === modal) {
            modal.classList.remove('active');
        }
    });
}

// 页面加载完成后获取排行榜数据
$(document).ready(function() {
    fetchLeaderboard();

    // 绑定排行榜按钮点击事件
    document.getElementById('leaderboard-button').addEventListener('click', showLeaderboardModal);
});